<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="年度:" prop="nd">
            <el-input
              v-model="queryParams.nd"
              placeholder="请输入年度"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称:" prop="xmName">
            <el-input
              v-model="queryParams.xmName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目编号:" prop="xmBh">
            <el-input
              v-model="queryParams.xmBh"
              placeholder="请输入项目编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="记录开始时间:">
            <el-date-picker
              v-model="daterangeJlQTime"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录结束时间:">
            <el-date-picker
              v-model="daterangeJlZTime"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fztz:clxhtb:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fztz:clxhtb:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fztz:clxhtb:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fztz:clxhtb:export']"
        >导出Excel
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-delete"
          :disabled="single"
          @click="handleDocx"
        >导出docx
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row height="300"
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              class="fixedTableTwo" v-loading="loading" :data="clxhtbList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="年度" align="center" prop="nd" width="60"/>
      <el-table-column label="项目名称" align="center" prop="xmName">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link type="primary">{{ '(第' + scope.row.jlCs + '次)' + scope.row.xmName }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="项目编号" align="center" prop="xmBh"/>
      <el-table-column label="记录开始时间" align="center" prop="jlQTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jlQTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录结束时间" align="center" prop="jlZTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jlZTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录次数" align="center" prop="jlCs"/>
      <el-table-column label="填报时间" align="center" prop="tbTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.tbTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目负责人" align="center" prop="xmFzName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fztz:clxhtb:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fztz:clxhtb:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改材料消耗填报对话框 -->
    <vxe-modal :title="title" v-model="open" width="85%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="150px">
        <el-tabs type="border-card" v-model="activeName">
          <!-- 基本资料 -->
          <el-tab-pane name="jbzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 基本资料</span>
            <div v-if="activeName === 'jbzl'" style="height: 72vh; overflow-y: auto;">
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">基本资料</span>
                </div>
                <el-form-item label="项目名称" prop="xmName" @focus="selectKt">
                  <el-input v-model="form.xmName" placeholder="请关联科研项目" @focus="selectKt()"
                            :suffix-icon="'el-icon-search'">
                    <el-button slot="append" icon="el-icon-search" @click="getXmXq" style="color: #1890ff">查看立项资料
                    </el-button>
                  </el-input>
                </el-form-item>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目编号" prop="xmBh">
                      <el-input v-model="form.xmBh" placeholder="请输入项目编号"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="记录时间" prop="jlQTime">
                      <el-date-picker clearable style="width: 45%;"
                                      v-model="form.jlQTime"
                                      type="date"
                                      value-format="yyyy-MM-dd">
                      </el-date-picker>
                      至
                      <el-date-picker @change="getXmsbIdCount" clearable style="width: 45%;"
                                      v-model="form.jlZTime"
                                      type="date"
                                      value-format="yyyy-MM-dd">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="8">
                    <el-form-item label="项目负责人" prop="xmFzName">
                      <el-input v-model="form.xmFzName" placeholder="请输入项目负责人"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="填报时间" prop="tbTime">
                      <el-date-picker clearable style="width: 100%;"
                                      v-model="form.tbTime"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="请选择填报时间">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="记录次数" prop="jlCs">
                      <el-input disabled v-model="form.jlCs" placeholder="选择课题及记录截止时间后自动带入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="本次科研目的" prop="bcKyMd">
                  <el-input :rows="5" v-model="form.bcKyMd" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-form-item label="本次科研活动情况" prop="bcKyHdQk">
                  <el-input :rows="5" v-model="form.bcKyHdQk" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-form-item label="本次科研结果" prop="bcKyJg">
                  <el-input :rows="5" v-model="form.bcKyJg" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-form-item label="本次参与的科研人员" prop="bcCyKyRy">
                  <el-input :rows="5" v-model="form.bcCyKyRy" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 实(试)验过程消耗的材料信息 -->
          <el-tab-pane name="xhcl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 实(试)验过程消耗的材料信息</span>
            <div v-if="activeName === 'xhcl'" style="height: 72vh; overflow-y: auto;">
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">实(试)验过程消耗的材料信息</span>
                </div>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="AddClxhtbXhcl">添加
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteClxhtbXhcl">删除
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-tooltip placement="top" effect="light">
                      <div slot="content">在Excel中选中需要粘贴的表格信息<br/>点击此按钮后<br/>ctry + v<br/>即可粘贴
                      </div>
                      <el-button type="warning" icon="el-icon-document-copy" size="mini"
                                 @click="handleXhClPasteFromExcel">粘贴Excel
                      </el-button>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="warning" icon="el-icon-download" size="mini" @click="handleDownloadXhClExcel">
                      粘贴模板下载
                    </el-button>
                  </el-col>
                </el-row>
                <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                          show-summary sum-text="汇总" :summary-method="getSummaries"
                          height="57vh" :data="clxhtbXhclList" :row-class-name="rowClxhtbXhclIndex"
                          @selection-change="handleClxhtbXhclSelectionChange" ref="clxhtbXhcl">
                  <el-table-column type="selection" width="50" align="center"/>
                  <el-table-column label="序号" align="center" prop="index" width="50"/>
                  <el-table-column label="物领料月份" align="center" prop="wLlYf" width="130">
                    <template slot-scope="scope">
                      <el-date-picker clearable style="width: 100%;" v-model="scope.row.wLlYf" type="month"
                                      value-format="yyyy-MM"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="物料名称" align="center" prop="wlName" width="150">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.wlName"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="用途" align="center" prop="yt" width="150">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.yt">
                        <el-option
                          v-for="dict in dict.type.fztz_clxhtb_yt"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="规格" align="center" prop="gg">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.gg"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="单位" align="center" prop="dw">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.dw"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="单价" align="center" prop="dj">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.dj"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="数量" align="center" prop="sl">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.sl"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="总价" align="center" prop="zj">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.zj"/>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="其中: 消耗">
                    <el-table-column label="数量" align="center" prop="xhSl">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.xhSl"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="金额" align="center" prop="xhJe">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.xhJe"/>
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column align="center" label="其中产品组成部分">
                    <el-table-column label="数量" align="center" prop="xcCpSl">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.xcCpSl"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="金额" align="center" prop="xcCpJe">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.xcCpJe"/>
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column align="center" label="形成下角料、残次品、中间试制品等">
                    <el-table-column label="数量" align="center" prop="xcXjlSl">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.xcXjlSl"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="金额" align="center" prop="xcXjlJe">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.xcXjlJe"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="处置收入" align="center" prop="xcXjlCzsr">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.xcXjlCzsr"/>
                      </template>
                    </el-table-column>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 实(试)验过程使用的设备信息 -->
          <el-tab-pane name="sysb" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 实(试)验过程使用的设备信息</span>
            <div v-if="activeName === 'sysb'" style="height: 72vh; overflow-y: auto;">
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">实(试)验过程使用的设备信息</span>
                </div>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="AddClxhtbSysb">添加
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteClxhtbSysb">删除
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-tooltip placement="top" effect="light">
                      <div slot="content">在Excel中选中需要粘贴的表格信息<br/>点击此按钮后<br/>ctry + v<br/>即可粘贴
                      </div>
                      <el-button type="warning" icon="el-icon-document-copy" size="mini"
                                 @click="handleSySbPasteFromExcel">粘贴Excel
                      </el-button>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="warning" icon="el-icon-download" size="mini" @click="handleDownloadSySbExcel">
                      粘贴模板下载
                    </el-button>
                  </el-col>
                </el-row>
                <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                          height="57vh" :data="clxhtbSysbList" :row-class-name="rowClxhtbSysbIndex"
                          @selection-change="handleClxhtbSysbSelectionChange" ref="clxhtbSysb">
                  <el-table-column type="selection" width="50" align="center"/>
                  <el-table-column label="序号" align="center" prop="index" width="50"/>
                  <el-table-column label="名称" align="center" prop="mc">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.mc" placeholder="请输入名称"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="型号" align="center" prop="xh">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.xh" placeholder="请输入型号"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="资产类别" align="center" prop="zcLb">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.zcLb" placeholder="请输入资产类别"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="用途" align="center" prop="yt">
                    <template slot-scope="scope">
                      <el-input :rows="1" type="textarea" v-model="scope.row.yt" placeholder="请输入用途"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" align="center" prop="bz">
                    <template slot-scope="scope">
                      <el-input :rows="1" type="textarea" v-model="scope.row.bz" placeholder="请输入备注"/>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 附件资料 -->
          <el-tab-pane name="fjzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 附件资料</span>
            <div v-if="activeName === 'fjzl'" style="height: 72vh; overflow-y: auto;">
              <el-card class="box-card" shadow="never">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">附件资料</span>
                </div>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <!-- 上传按钮 -->
                    <el-button size="mini" icon="el-icon-upload" type="primary" @click="clxhtbFileUpload">上传
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteClxhtbFj">删除
                    </el-button>
                  </el-col>
                </el-row>
                <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                          :data="clxhtbFjList" :row-class-name="rowClxhtbFjIndex"
                          @selection-change="handleClxhtbFjSelectionChange" ref="clxhtbFj">
                  <el-table-column type="selection" width="50" align="center"/>
                  <el-table-column label="序号" align="center" prop="index" width="50"/>
                  <el-table-column show-overflow-tooltip label="文件名称" align="center" prop="fileName"
                                   :formatter="getFileNames"/>
                  <el-table-column label="文件大小" align="center" prop="fileSize"/>
                  <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handlePreview(scope.row)"
                      >预览
                      </el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleDownload(scope.row)"
                      >下载
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 科研项目选择 -->
    <HtXzKt ref="ktXz"/>

    <!-- 查看科研项目详情 -->
    <Xmxq ref="xmxq"/>

    <!-- 材料消耗填报附件上传弹窗 -->
    <vxe-modal title="附件上传" v-model="fjUpload" width="25%" showFooter show-zoom resize @close="fjClose">
      <el-upload
        align="center"
        class="upload-demo"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="20"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :headers="headers"
        ref="fileUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          请上传
          <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button v-if="allFilesUploaded === false" size="mini" type="primary" @click="fjUpload = false">关 闭
        </el-button>
        <el-button v-if="allFilesUploaded === true" size="mini" type="primary" @click="fjClose">上传完成, 关闭
        </el-button>
      </div>

    </vxe-modal>

    <!-- 预览组件 -->
    <KkFileView ref="preview"/>

    <!-- 材料消耗填报详情 -->
    <ClXhTbXq ref="clXhTbXq"/>

  </div>
</template>

<script>
import {
  addClxhtb,
  delClxhtb,
  deleteClxhtbFjByFjIds,
  exportClxhtbWord,
  getClxhtb,
  getClXhTbId,
  insertClxhtbFjByClxhtbId,
  listClxhtb,
  selectClxhtbFjList,
  selectClxhtbSySbByClxhtbId,
  selectClxhtbXhclByClxhtbId,
  selectXmsbIdCountByClxhtb,
  updateClxhtb
} from "@/api/fztz/clxhtb";
import HtXzKt from "@/views/components/ktXz/HtXzKt.vue";
import Xmxq from "@/views/xmgl/lxgl/xmsb/components/xmxq.vue";
import {getToken} from "@/utils/auth";
import KkFileView from "@/views/components/KKFileView/kkFileView.vue";
import ClXhTbXq from "@/views/fztz/clxhtb/components/ClXhTbXq.vue";

export default {
  name: "Clxhtb",
  dicts: ['fztz_clxhtb_yt'],
  components: {ClXhTbXq, KkFileView, Xmxq, HtXzKt},
  provide() {
    return {
      updateXmsbId: (val) => {
        //项目名称
        this.form.xmName = val.ktName
        //项目申报ID
        this.form.xmsbId = val.xmsbId
        //项目编号
        this.form.xmBh = val.ktBh
        //项目负责人
        this.form.xmFzName = val.fzName
        this.$refs['formDialog'].validateField('xmName');
        this.$refs['formDialog'].validateField('xmFzName');
        this.getXmsbIdCount()
      },

    }
  },
  data() {
    return {
      xg: false, //判断是新增还是修改 (false新增 true修改)
      allFilesUploaded: false, // 添加这个来追踪所有文件是否上传完成
      fjUpload: false, //附件上传弹窗
      //要修改的 材料消耗填报id
      clxhtbIdEdit: "",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      fileList: [],
      headers: {Authorization: "Bearer " + getToken()},
      number: 0,
      uploadList: [],
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "docx", "zip"],
      getClXhTbId: null, //从后端获取的材料消耗填报主键ID (UUID)
      activeName: 'jbzl', //初始打开的标签页
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedClxhtbFj: [],
      // 材料消耗子表选中数据
      checkedClxhtbXhcl: [],
      // 使用设备子表选中数据
      checkedClxhtbSysb: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料消耗填报表格数据
      clxhtbList: [],
      // 材料消耗填报附件表格数据
      clxhtbFjList: [],
      // 实(试)验过程消耗的材料表格数据
      clxhtbXhclList: [],
      // 实(试)验过程使用的设备表格数据
      clxhtbSysbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文件大小时间范围
      daterangeJlQTime: [],
      // 文件大小时间范围
      daterangeJlZTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nd: null,
        xmsbId: null,
        xmName: null,
        xmBh: null,
        jlQTime: null,
        jlZTime: null,
        xmFzName: null,
        idWhere: null,
        userId: this.$store.state.user.id,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nd: [{required: true, message: "年度不能为空", trigger: "blur"}],
        xmName: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
        xmBh: [{required: true, message: "项目编号不能为空", trigger: "blur"}],
        jlQTime: [{required: true, message: "记录起时间不能为空", trigger: "blur"}],
        jlZTime: [{required: true, message: "记录止时间不能为空", trigger: "blur"}],
        xmFzName: [{required: true, message: "项目负责人不能为空", trigger: "blur"}],
        tbTime: [{required: true, message: "填报时间不能为空", trigger: "blur"}],
        // jlCs: [{required: true, message: "记录次数不能为空", trigger: "blur"}],
        bcKyMd: [{required: true, message: "本次科研目的不能为空", trigger: "blur"}],
        bcKyHdQk: [{required: true, message: "本次科研活动情况不能为空", trigger: "blur"}],
        bcKyJg: [{required: true, message: "本次科研结果不能为空", trigger: "blur"}],
        bcCyKyRy: [{required: true, message: "本次参与的科研人员不能为空", trigger: "blur"}],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //导出word按钮操作
    handleDocx() {
      const row = this.selectedRow; // 获取当前选中的行
      const queryParams = this.queryParams;
      const clxhtbId = row.clxhtbId;
      this.$confirm('是否确认导出word文档?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true
        return exportClxhtbWord(queryParams, clxhtbId);
      }).then(response => {
        this.$download.resource('/profile/upload/' + response.msg);
        this.loading = false
      }).catch(() => {
      });
    },
    //打开材料消耗填报详情组件
    handleButtonClick(row) {
      this.$refs.clXhTbXq.handleOpen(row)
    },
    // 打开预览组件
    handlePreview(row) {
      this.$refs.preview.handleOpen(row);
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName;
      // 默认方法
      this.$download.resource(resource);
    },
    // 获取文件名原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop(); // 返回文件名部分
    },
    //关闭上传附件弹窗后
    fjClose() {
      this.fileList = []
      this.allFilesUploaded = false
      this.fjUpload = false
    },
    //上传文件之前的钩子
    handleBeforeUpload(file) {
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      let that = this;
      if (res.code === 200) {
        this.uploadList.push({name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size)});
        let xzItemFile = {
          "clxhtbId": that.getClXhTbId,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        let xgItemFile = {
          "clxhtbId": that.clxhtbIdEdit,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        if (this.xg === false) {
          // 点击新增按钮的上传
          insertClxhtbFjByClxhtbId(xzItemFile).then(resFil => {
            that.getClxhtbFjList();
          })
        } else if (this.xg === true) {
          // 点击修改按钮的上传
          insertClxhtbFjByClxhtbId(xgItemFile).then(resFil => {
            that.getClxhtbFjList();
          })
        }
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
      this.allFilesUploaded = true
      this.$modal.msgSuccess("上传成功")
      // this.fjShangChuan = false
    },
    getClxhtbFjList() {
      let that = this;
      if (this.xg === false) {
        //点击新增 上传文件后的文件列表
        selectClxhtbFjList(that.getClXhTbId).then(resFileList => {
          that.clxhtbFjList = resFileList.data;
        })
      } else {
        //点击修改 上传文件后的文件列表
        selectClxhtbFjList(that.clxhtbIdEdit).then(resFileList => {
          that.clxhtbFjList = resFileList.data;
        })
      }
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.fileList = this.fileList.map(item => {
          // 使用split方法去除name中的特定前缀
          item.name = item.name.split('/').pop();
          return item;
        });
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    //材料消耗填报附件上传按钮
    clxhtbFileUpload() {
      this.fjUpload = true;
    },
    //查询这个项目申报ID在记录表中出现过几次
    getXmsbIdCount() {
      if (this.form.xmsbId && this.form.jlZTime) {
        selectXmsbIdCountByClxhtb(this.form.xmsbId).then(res => {
          this.form.jlCs = res.xmsbIdCount + 1
        })
      } else {
        console.log()
      }
    },
    //使用设备excel粘贴模板下载
    handleDownloadSySbExcel() {
      let a = document.createElement('a');
      a.href = `/static/实(试)验过程使用的设备 粘贴模板.xlsx`;
      a.download = '实(试)验过程使用的设备 粘贴模板.xlsx';
      a.click();
    },
    //消耗材料excel粘贴模板下载
    handleDownloadXhClExcel() {
      let a = document.createElement('a');
      a.href = `/static/实(试)验过程消耗的材料 粘贴模板.xlsx`;
      a.download = '实(试)验过程消耗的材料 粘贴模板.xlsx';
      a.click();
    },
    //消耗材料表 合计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 4) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        // 对sqzz 和 zcje 这两列进行总计核算。
        if (column.property === 'zj' || column.property === 'xhJe' || column.property === 'xcCpJe'
          || column.property === 'xcXjlJe' || column.property === 'xcXjlCzsr') {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '---'
          }
        }
      });
      return sums;
    },
    //打开科研项目详情
    getXmXq() {
      if (this.form.xmsbId == null || this.form.xmsbId == undefined || this.form.xmsbId == '') {
        this.$modal.alertWarning("请先选择项目！");
      } else {
        let row = {
          xmsbId: this.form.xmsbId
        }
        this.$refs.xmxq.handleOpen(row);
      }
    },
    // 打开选择科研项目弹窗
    selectKt() {
      this.$refs.ktXz.handleOpen();
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询材料消耗填报列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeJlQTime && '' != this.daterangeJlQTime) {
        this.queryParams.params["beginJlQTime"] = this.daterangeJlQTime[0];
        this.queryParams.params["endJlQTime"] = this.daterangeJlQTime[1];
      }
      if (null != this.daterangeJlZTime && '' != this.daterangeJlZTime) {
        this.queryParams.params["beginJlZTime"] = this.daterangeJlZTime[0];
        this.queryParams.params["endJlZTime"] = this.daterangeJlZTime[1];
      }
      listClxhtb(this.queryParams).then(response => {
        this.clxhtbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        clxhtbId: this.getClXhTbId,
        nd: new Date().getFullYear(), //当前年
        xmsbId: null,
        xmName: null,
        xmBh: null,
        jlQTime: null,
        jlZTime: null,
        xmFzName: null,
        tbTime: this.getCurrentDate(), //当前年月日
        jlCs: null,
        bcKyMd: null,
        bcKyHdQk: null,
        bcKyJg: null,
        bcCyKyRy: null,
        idWhere: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.clxhtbFjList = [];
      this.clxhtbXhclList = [];
      this.clxhtbSysbList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeJlQTime = [];
      this.daterangeJlZTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let ids = selection.map(item => item.clxhtbId)
      if (ids.length === 1) {
        this.ids = ids[0]
      } else {
        this.ids = ids
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.xg = false
      getClXhTbId().then(res => {
        this.getClXhTbId = res.msg
        this.reset();
      })
      this.activeName = 'jbzl'
      this.open = true;
      this.title = "添加材料消耗填报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.xg = true
      const clxhtbId = row.clxhtbId || this.ids
      this.clxhtbIdEdit = row.clxhtbId || this.ids
      getClxhtb(clxhtbId).then(response => {
        this.form = response.data;
        this.clxhtbFjList = response.data.clxhtbFjList;
        selectClxhtbXhclByClxhtbId(clxhtbId).then(res => {
          this.clxhtbXhclList = res.data.clxhtbXhclList;
        })
        selectClxhtbSySbByClxhtbId(clxhtbId).then(res => {
          this.clxhtbSysbList = res.data.clxhtbSysbList;
        })
        this.activeName = 'jbzl'
        this.open = true;
        this.title = "修改材料消耗填报";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.clxhtbFjList = this.clxhtbFjList;
          this.form.clxhtbXhclList = this.clxhtbXhclList;
          this.form.clxhtbSysbList = this.clxhtbSysbList;
          if (this.form.idWhere != null) {
            updateClxhtb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.xg = false
            });
          } else {
            addClxhtb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const clxhtbIds = row.clxhtbId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delClxhtb(clxhtbIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 材料消耗填报附件序号 */
    rowClxhtbFjIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 材料消耗填报附件删除按钮操作 */
    handleDeleteClxhtbFj() {
      if (this.checkedClxhtbFj.length == 0) {
        this.$modal.msgError("请先选择要删除的材料消耗填报附件数据");
      } else {
        const fjIds = this.checkedClxhtbFj;
        this.$modal.confirm('确定删除选中记录？').then(function () {
          return deleteClxhtbFjByFjIds(fjIds);
        }).then(() => {
          if (this.xg == false) {
            selectClxhtbFjList(this.getClXhTbId).then(resFileList => {
              this.clxhtbFjList = resFileList.data;
            })
          } else {
            getClxhtb(this.clxhtbIdEdit).then(response => {
              this.clxhtbFjList = response.data.clxhtbFjList;
            });
          }
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },
    /** 复选框选中数据 */
    handleClxhtbFjSelectionChange(selection) {
      this.checkedClxhtbFj = selection.map(item => item.fjId)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fztz/clxhtb/export', {
        ...this.queryParams
      }, `clxhtb_${new Date().getTime()}.xlsx`)
    },
    /** 实(试)验过程消耗的材料序号 */
    rowClxhtbXhclIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    // 实(试)验过程消耗的材料excel 粘贴
    handleXhClPasteFromExcel() {
      const pasteHandler = (e) => {
        e.preventDefault();
        const clipboardData = e.clipboardData || window.clipboardData;
        const pastedData = clipboardData.getData('text/plain').trim();
        if (pastedData) {
          const rows = pastedData.split('\n');
          const parsedData = rows.map(row => row.split('\t').map(cell => cell.replace(/\r$/, '')));
          parsedData.forEach(row => {
            if (row.length >= 1) {
              // 调用 handleAddClxhtbXhcl 并传递解析后的数据
              this.handleAddClxhtbXhcl({
                wLlYf: row[0],
                wlName: row[1],
                yt: row[2],
                gg: row[3],
                dw: row[4],
                dj: row[5],
                sl: row[6],
                zj: row[7],
                xhSl: row[8],
                xhJe: row[9],
                xcCpSl: row[10],
                xcCpJe: row[11],
                xcXjlSl: row[12],
                xcXjlJe: row[13],
                xcXjlCzsr: row[14],
              });
            }
          });
          console.log("解析并添加后的数据：", this.clxhtbXhclList);
        }
        document.removeEventListener('paste', pasteHandler);
      };
      document.addEventListener('paste', pasteHandler, {once: true});
    },
    AddClxhtbXhcl() {
      let obj = {
        wLlYf: "",
        wlName: "",
        yt: "",
        gg: "",
        dw: "",
        dj: "",
        sl: "",
        zj: "",
        xhSl: "",
        xhJe: "",
        xcCpSl: "",
        xcCpJe: "",
        xcXjlSl: "",
        xcXjlJe: "",
        xcXjlCzsr: "",
      };
      this.clxhtbXhclList.push(obj);
    },
    /** 实(试)验过程消耗的材料添加按钮操作 */
    handleAddClxhtbXhcl(data) {
      // 修改此方法以接受一个数据参数
      if (data) {
        // 直接使用传入的数据
        this.clxhtbXhclList.push(data);
      } else {
        // 如果没有传入数据，则添加一个空对象
        let obj = {
          wLlYf: "",
          wlName: "",
          yt: "",
          gg: "",
          dw: "",
          dj: "",
          sl: "",
          zj: "",
          xhSl: "",
          xhJe: "",
          xcCpSl: "",
          xcCpJe: "",
          xcXjlSl: "",
          xcXjlJe: "",
          xcXjlCzsr: "",
        };
        this.clxhtbXhclList.push(obj);
      }
      // let obj = {};
      // obj.wLlYf = "";
      // obj.wlName = "";
      // obj.yt = "";
      // obj.gg = "";
      // obj.dw = "";
      // obj.dj = "";
      // obj.sl = "";
      // obj.zj = "";
      // obj.xhSl = "";
      // obj.xhJe = "";
      // obj.xcCpSl = "";
      // obj.xcCpJe = "";
      // obj.xcXjlSl = "";
      // obj.xcXjlJe = "";
      // obj.xcXjlCzsr = "";
      // this.clxhtbXhclList.push(obj);
    },
    /** 实(试)验过程消耗的材料删除按钮操作 */
    handleDeleteClxhtbXhcl() {
      if (this.checkedClxhtbXhcl.length == 0) {
        this.$modal.msgError("请先选择要删除的实(试)验过程消耗的材料数据");
      } else {
        const clxhtbXhclList = this.clxhtbXhclList;
        const checkedClxhtbXhcl = this.checkedClxhtbXhcl;
        this.clxhtbXhclList = clxhtbXhclList.filter(function (item) {
          return checkedClxhtbXhcl.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleClxhtbXhclSelectionChange(selection) {
      this.checkedClxhtbXhcl = selection.map(item => item.index)
    },
    /** 实(试)验过程使用的设备序号 */
    rowClxhtbSysbIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    //实(试)验过程使用的设备excel 粘贴
    handleSySbPasteFromExcel() {
      const pasteHandler = (e) => {
        e.preventDefault();
        const clipboardData = e.clipboardData || window.clipboardData;
        const pastedData = clipboardData.getData('text/plain').trim();
        if (pastedData) {
          const rows = pastedData.split('\n');
          const parsedData = rows.map(row => row.split('\t').map(cell => cell.replace(/\r$/, '')));
          parsedData.forEach(row => {
            if (row.length >= 1) {
              // 调用handleAddClxhtbSysb并传递解析后的数据
              this.handleAddClxhtbSysb({
                mc: row[0],
                xh: row[1],
                zcLb: row[2],
                yt: row[3],
                bz: row[4],
              });
            }
          });
          console.log("解析并添加后的数据：", this.clxhtbSysbList);
        }
        document.removeEventListener('paste', pasteHandler);
      };
      document.addEventListener('paste', pasteHandler, {once: true});
    },
    /** 实(试)验过程使用的设备添加按钮操作 */
    AddClxhtbSysb() {
      let obj = {};
      obj.mc = "";
      obj.xh = "";
      obj.zcLb = "";
      obj.yt = "";
      obj.bz = "";
      this.clxhtbSysbList.push(obj);
    },
    /** 实(试)验过程使用的设备添加按钮操作 */
    handleAddClxhtbSysb(data) {
      // 修改此方法以接受一个数据参数
      if (data) {
        // 直接使用传入的数据
        this.clxhtbSysbList.push(data);
      } else {
        // 如果没有传入数据，则添加一个空对象
        let obj = {
          mc: "",
          xh: "",
          zcLb: "",
          yt: "",
          bz: "",
        };
        this.clxhtbSysbList.push(obj);
      }
      // let obj = {};
      // obj.mc = "";
      // obj.xh = "";
      // obj.zcLb = "";
      // obj.yt = "";
      // obj.bz = "";
      // this.clxhtbSysbList.push(obj);
    },
    /** 实(试)验过程使用的设备删除按钮操作 */
    handleDeleteClxhtbSysb() {
      if (this.checkedClxhtbSysb.length == 0) {
        this.$modal.msgError("请先选择要删除的实(试)验过程使用的设备数据");
      } else {
        const clxhtbSysbList = this.clxhtbSysbList;
        const checkedClxhtbSysb = this.checkedClxhtbSysb;
        this.clxhtbSysbList = clxhtbSysbList.filter(function (item) {
          return checkedClxhtbSysb.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleClxhtbSysbSelectionChange(selection) {
      this.checkedClxhtbSysb = selection.map(item => item.index)
    },
  }
};
</script>
